<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/26 0026
 * Time: 22:21
 */
class Worker
{

    protected $socket;

    public $connect;

    public $message;

    public function __construct($socket_address)
    {
        $this->socket = stream_socket_server($socket_address);
    }

    public function accept()
    {
        while (1) {
            if (pcntl_fork() == 0) {

                $client = stream_socket_accept($this->socket);
                if ($client && is_callable($this->connect)) {
                    call_user_func_array($this->connect, array($client, '触发连接'));
                }
                $clientData = fread($client, 65535);
                if (!empty($clientData) && is_callable($this->message)) {
                    call_user_func_array($this->message, array($client, '触发消息事件'));
                }
                fclose($client);
            }
        }
    }

    public function fork()
    {

        for ($i = 0; $i < 10; $i++) {
            $pid = pcntl_fork();
            if ($pid < 0) {
                exit('创建失败');
            } elseif ($pid > 0) {
                //父进程空间 返回子进程ID


            } elseif ($pid == 0) { // 返回0子进程空间
//                sleep(20);
                $this->accept();
            }
        }

        $status = 0;
        $pid = pcntl_wait($status); //结束的子进程信息，阻塞状态
        echo "子进程ID=" . $pid . PHP_EOL;
    }

    public function start()
    {
        $this->fork();

    }

}

$worker = new Worker('tcp://0.0.0.0:9501');

$worker->connect = function ($client, $args) {
    var_dump($client, $args);
};
$worker->message = function ($client, $args) {
    var_dump($client, $args);
    $out = "HTTP/1.1\r\n";
    $out .= "Host: test.com\r\n";

    $out .= "name:longqiqi\r\n";
    $out .= "Connection: Close\r\n\r\n";

    fwrite($client, $out);
};
$worker->start();